/**
 * 
 */
package co.fitstart.market.handler.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.support.Result;
import com.demo2do.core.support.sms.handler.SmsHandler;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.market.entity.MessageType;
import co.fitstart.market.handler.SmsSender;

/**
 * @author downpour
 *
 */
@Component("smsSender")
public class SmsSenderImpl implements SmsSender {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);
    
    @Autowired
    private SmsHandler smsHandler;

    @Value("#{config['sms.company']}")
    private String company;

    /* (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#generateVerifyCode(java.lang.String)
     */
    public String generateVerifyCode(String mobile) {
        return RandomStringUtils.randomNumeric(6);
    }

    /* (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendVerifyCode(java.lang.String, java.lang.String)
     */
    public boolean sendVerifyCode(String mobile, String code) {
        
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.VERIFY_CODE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("code", code);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            logger.trace("#onSendVerifyCode - sending verify code to mobile: [{}], verify code is: [{}]", mobile, code);
            
            // Send message by calling sms handler
            result = smsHandler.sendShortMessage(mobile, message);
            
        }
        
        return result.isValid();
        
    }
    
    /* (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#checkVerifyCode(java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean checkVerifyCode(String mobile, String code, String token) {
        String vtoken = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "fitstart"));
        return org.apache.commons.lang3.StringUtils.equals(vtoken, token);
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendTradingNotice(java.lang.String, java.lang.String, java.lang.String)
     */
    public void sendTradingNotice(String mobile, String product, String order) {
        
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.TRADING_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("product", product);
            values.put("order", order);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendTradingNotice() error", JsonUtils.toJsonString(result));
            }
        }
        
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendBuyCourseNotice(java.lang.String, java.lang.String)
     */
    public void sendBuyCourseNotice(String mobile, String product) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.NEWORDER_NOTICE);
        
        if (template != null) {
            
            String today = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("time", today);
            values.put("course", product);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendBuyCourseNotice() error", JsonUtils.toJsonString(result));
            }
        }
        
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendIndividualRoundNotice(java.lang.String, java.lang.String, java.lang.String)
     */
    public void sendIndividualRoundNotice(String mobile, String time, String roomtype) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.COURSE_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("time", time);
            values.put("roomtype", roomtype);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendIndividualRoundNotice() error", JsonUtils.toJsonString(result));
            }
        }
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendExperienceRoundNotice(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    public void sendExperienceRoundNotice(String mobile, String student, String time, String coach,
            String coachMobile) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.FIRSTTIME_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("username", student);
            values.put("time", time);
            values.put("coachname", coach);
            values.put("coachmobile", coachMobile);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendExperienceRoundNotice() error", JsonUtils.toJsonString(result));
            }
        }
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendOrderCoachNotice(java.lang.String, java.lang.String, java.lang.String)
     */
    public void sendOrderCoachNotice(String mobile, String student, String webchatCode) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.COACH_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("username", student);
            values.put("wechatcode", webchatCode);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendOrderCoachNotice() error", JsonUtils.toJsonString(result));
            }
        }
    }

    @Override
    public void sendInviteUserNotice(String mobile, int amount) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.MARKET_INVITE_USER_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("amountAlready", String.valueOf(amount));
            values.put("amountNeeded", String.valueOf(3-amount));
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendOrderCoachNotice() error", JsonUtils.toJsonString(result));
            }
        }
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.market.handler.SmsSender#sendFullInviteUserNotice(java.lang.String, java.lang.String)
     */
    public void sendFullInviteUserNotice(String mobile, int amount, String url) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.MARKET_FULL_INVITE_USER_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("amountAlready", String.valueOf(amount));
            values.put("entryLink", url);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendOrderCoachNotice() error", JsonUtils.toJsonString(result));
            }
        }
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.market.handler.SmsSender#sendAchievementNotice(java.lang.String, int, java.lang.String)
     */
    public void sendAchievementNotice(String mobile, int signinDays, String url) {
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.MARKET_RECEIVE_ACHIEVEMENT_NOTICE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("amountCompleted", String.valueOf(signinDays));
            values.put("achievementLink", url);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            // Send message
            result = smsHandler.sendShortMessage(mobile, message);
            
            if(!result.isValid()) {
                logger.error("sendOrderCoachNotice() error", JsonUtils.toJsonString(result));
            }
        }
    }

}
